package com.jyh.service.basicBi;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jyh.config.BaseAction;
import com.jyh.db.entity.JyhBasicData;
import com.jyh.db.entity.JyhBasicDataExample;
import com.jyh.db.mapper.JyhBasicDataMapper;

@Service
public class DataRecoveryService extends BaseAction {
	@Autowired
	private JyhBasicDataMapper dataMapper;
	@Autowired
	private BasicService basicService;

	public void backdoorTrot1(String time1, String time2, HttpSession session) {
		String userName = session.getAttribute("username") + "";
		logger.warn("username:" + userName + ",更新渠道投资日报数据");
		logger.warn("更新渠道投资日报数据时间time1:" + time1 + ",time2:" + time2);
		JyhBasicDataExample dataExample = new JyhBasicDataExample();
		dataExample.createCriteria().andTimesBetween(time1, time2);
		dataMapper.deleteByExample(dataExample);
		try {
			if (time1.equals(time2)) {
				try {
					JyhBasicData vo = basicService.oldServe(time1);
					dataMapper.insert(vo);
				} catch (Exception e) {
					logger.error("---------- 渠道投资日报定时器执行报错结束----------：" + e.getMessage());
				}
				logger.info("----------  渠道投资日报定时器日结束----------");
			} else {
				List<String> list = timeDifference(time1, time2);
				for (int i = 0; i < list.size(); i++) {

					JyhBasicData vo = basicService.oldServe(list.get(i));
					dataMapper.insert(vo);
				}
			}
		} catch (Exception e) {
			logger.error("---------- 渠道投资日报定时器执行报错结束----------：" + e.getMessage());
			throw new RuntimeException("测试事务异常回滚");
			
		}
		logger.info("----------  渠道投资日报定时器日结束----------");
	}

	/**
	 * 获取时间差
	 * 
	 * @param time1
	 * @param time2
	 * @return
	 */
	private List<String> timeDifference(String time1, String time2) {
		List<String> list = new ArrayList<String>();
		String time = time1;
		for (int i = 0; i < 1000; i++) {
			Date beginDate = null;
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			String etime = "";
			try {
				beginDate = formatter.parse(time);
				Calendar date = Calendar.getInstance();
				date.setTime(beginDate);
				date.set(Calendar.DATE, date.get(Calendar.DATE) + i);
				Date endDate = formatter.parse(formatter.format(date.getTime()));
				etime = formatter.format(endDate);
			} catch (java.text.ParseException e) {
				e.printStackTrace();
			}
			list.add(etime);
			if (time2.equals(etime)) {
				break;
			}
		}
		return list;
	}

}
